<?php
/**
 * Class descript.
 * User: chan
 * Date: 2017/10/26 15:29
 */
namespace app\api\controller;
use think\Db;
use app\api\model\UserAccount;
use app\api\model\Income;
use app\api\model\Team;

class User extends Base
{
    /**
     * 获取个人中心信息
     */
    public function getPersonal()
    {
        $input = input();
        if (empty($input['uid'])){
            return $this->ajaxReturn('',-1,'未定义uid');
        }
        $data = [];
        $where = [];
        $userAccount = new UserAccount();
        $user = $userAccount->getUser(['id'=>$input['uid']]);//用户信息
        $data['user'] = $user;
        $rqpt = db('proportion')->where('tc_type',1)->value('num');//人气平台
        $rq_num = db('user_account')->where('status',0)->count();//注册人数
        $data['popularity'] = $rqpt + $rq_num;//人气平台
        $data['region'] = db('region')->where(['uid'=>$input['uid'],'status'=>2])->find();//区域代理
        $withdraw = db('withdraw')->where(['uid'=>$input['uid'],'status'=>1])->sum('money');//提现金额
        $data['withdraw'] = number_format($withdraw,2,".","");//保留2位小数

        $where['uid'] = ['=',$input['uid']];
        $where['status'] = ['=',2];
        $total_yj = $this->teamTotal($input['uid'],1);//总佣金
        $total_rw = db('income')->where($where)->sum('money');//总任务收入
        $data['total_sr'] = number_format(($total_yj + $total_rw),2,".","");//总收入

        $where['update_at'] = ['between',[strtotime(date('Y-m-d 00:00:00')),strtotime(date('Y-m-d 23:59:59'))]];
        $today_yj = $this->teamTotal($input['uid'],2);//今日佣金
        $today_rw = db('income')->where($where)->sum('money');//任务收入
        $data['today_sr'] = number_format(($today_yj + $today_rw),2,".","");//今天收入

        return $this->ajaxReturn($data);
    }
   /**
     * 获取个人资料
     */
    public function getUserInfo()
    {
        $input = input();
        if (empty($input['uid'])){
            return $this->ajaxReturn('',-1,'未定义uid');
        }
        $userAccount = new UserAccount();
        $user = $userAccount->getUser(['id'=>$input['uid']]);//用户信息

        return $this->ajaxReturn([$user]);
    }

   /**
     * 修改个人资料
     */
    public function modifyUserInfo()
    {
        $input = input();
        if (empty($input['uid'])){
            return $this->ajaxReturn('',-1,'未定义uid');
        }
        $data = [];
        if (!empty($_FILES['head_url'])){
            $file = request()->file('head_url');
            $info = $file->move('upload');
            if ($info) {
                $path = __ROOT__ . '/' . $info->getpathName();
                $data['head_url'] = $path;
            }
        }
        if (!empty($input['nick_name'])){
            $data['nick_name'] = $input['nick_name'];
        }
        if (!empty($input['real_name'])){
            $data['real_name'] = $input['real_name'];
        }
        if (!empty($input['phone'])){
            $data['phone'] = $input['phone'];
        }
        if (!empty($input['wx'])){
            $data['wx'] = $input['wx'];
        }
        if (!empty($input['sex'])){
            $data['sex'] = $input['sex'];
        }
        /*if (!empty($input['province'])){
            $data['province'] = $input['province'];
        }
        if (!empty($input['city'])){
            $data['city'] = $input['city'];
        }
        if (!empty($input['county'])){
            $data['county'] = $input['county'];
        }*/
        if (!empty($input['birthday'])){
            $data['birthday'] = strtotime($input['birthday']);
        }
        $data['update_at'] = time();
        $userAccount = new UserAccount();
        $res = $userAccount->modifyUser(['id'=>$input['uid']],$data);
        return $this->ajaxReturn(['status'=>$res]);
    }
   /**
     * 修改密码
     */
    public function modifyPassword() {
        $input = input();
        if (empty($input['uid'])){
            return $this->ajaxReturn('',-1,'未定义uid');
        }
        if (empty($input['old_password'])){
            return $this->ajaxReturn('',-1,'未定义old_password');
        }
        if (empty($input['new_password'])){
            return $this->ajaxReturn('',-1,'未定义new_password');
        }

        $userAccount = new UserAccount();
        $password = db('user_account')->where('id',$input['uid'])->value('password');
        $pass_bool = $userAccount->verification_hash($input['old_password'],$password);
        if(!$pass_bool){
            return $this->ajaxReturn('',-1,'旧密码不正确');
        }
        $data = [
            'password' => $userAccount->add_hash($input['new_password']),
            'update_at' => time()
        ];
        $res = $userAccount->modifyPassword(['id'=>$input['uid']],$data);
        return $this->ajaxReturn(['status'=>$res]);
    }

    /**
     * 我的团队
     */
    public function myTeam() {
        $input = input();
        if (empty($input['uid'])){
            return $this->ajaxReturn('',-1,'未定义uid');
        }
        $arr = [];
        // $team1_data = db('team')->where('recommend_id',$input['uid'])->select();//一级团队
        $Team = new Team();

        $team1_data = $Team->getTeamAll(['recommend_id'=>$input['uid']]);//一级团队

        $arr['level1'] = $team1_data;//一级团队

        foreach ($team1_data as $key => $value) {

            $value = $value->toArray();

            $team1_info = db('user_account')->where('id',$value['uid'])->field('head_url,nick_name')->find();//一级团队个人信息
     
            // $team2_data = db('team')->where('recommend_id',$value['uid'])->select();//二级团队
            $team2_data = $Team->getTeamAll(['recommend_id'=>$value['uid']]);//二级团队

            foreach ($team2_data as $k => $v) {
                $v = $v->toArray();
                $team2_info = db('user_account')->where('id',$v['uid'])->field('head_url,nick_name')->find();//二级团队个人信息

                // $team2_total = $this->total($v['uid']);
                $team2_teamSum = $this->totalSum($v['uid']);
                $team2_commission = $this->teamTotal($v['uid'],1);
 
                $v['head_url'] = $team2_info['head_url'];
                $v['nick_name'] = $team2_info['nick_name'];
                $v['teamSum'] = $team2_teamSum;
             /*   var_dump($v);die;*/
                $v['commission'] = $team2_commission;
                $arr['level2'][] = $v;
            }

            //一级团队一佣金
            /*$one_total = db('commission')->where('uid',$uid)->*/

            $team1_teamSum = $this->totalSum($value['uid']);
            $team1_commission = $this->teamTotal($value['uid'],1);

            $arr['level1'][$key]['head_url'] = $team1_info['head_url'];

            $arr['level1'][$key]['nick_name'] = $team1_info['nick_name'];
            $arr['level1'][$key]['teamSum'] = $team1_teamSum['teamSum'];
            $arr['level1'][$key]['commission'] = $team1_commission;
        }
        return $this->ajaxReturn($arr);
    }
    /**
     * 获取团队成员总数
     */
    public function totalSum($uid) {
        $data = [];
        $team_commission = 0;
        $t2_sum = 0;
        $team1_data = db('team')->where('recommend_id',$uid)->select();//一级团队
        $team1_sum = db('team')->where('recommend_id',$uid)->count();//一级团队总人数
        foreach ($team1_data as $key => $value) {
            $team2_sum = db('team')->where('recommend_id',$value['uid'])->count();//二级团队总人数
            $t2_sum = $t2_sum + $team2_sum;
        }
        $data['teamSum'] = $team1_sum + $t2_sum;//团队总人数
        return $data;
    }

    /**
     * 获取区域代理佣金
     */
    public function region_total($uid,$province='',$city='',$county='',$where='') {

        //判断是否区域代理
        $user = db('region')->where('uid',$uid)->find();
        if($user){

            $total = 0;

            $all_user = db('user_account')->field('id')->where('province',$province)->where('city',$city)->where('county',$county)->where('status',0)->where($where)->select();

            foreach ($all_user as $key => $v) {

               /* $task = db('commission')->where('uid',$v['id'])->where('type',1)->sum('money');//任务佣金*/

                $recharge = db('commission')->where('uid',$v['id'])->where('type',2)->sum('money');//充值佣金

             /*   $task_price = db('proportion')->where('tc_type',6)->value('tc_price');*/

                $recharge_price = db('proportion')->where('tc_type',7)->value('tc_price');

                /*$task = empty($task)?0:$task;*/
                $recharge = empty($recharge)?0:$recharge;
               /* $task_price = empty($task_price)?0:($task_price/100);*/
                $recharge_price = empty($recharge_price)?0:($recharge_price/100);

               /* $totaltemp = ($task*$task_price + $recharge*$recharge_price);*/
                $totaltemp = $recharge*$recharge_price;

                $total += $totaltemp;

            }

        }else{

            $total = 0;
        }

        return $total;

    }



    /**
     * 提现
     */
    public function withdraw() {
        $input = input();
        if (empty($input['uid'])){
            return $this->ajaxReturn('',-1,'未定义uid');
        }
        if (empty($input['type'])){
            return $this->ajaxReturn('',-1,'未定义type');
        }
        if (empty($input['name'])){
            return $this->ajaxReturn('',-1,'未定义name');
        }
        if (empty($input['number'])){
            return $this->ajaxReturn('',-1,'未定义number');
        }
        if (empty($input['money'])){
            return $this->ajaxReturn('',-1,'未定义money');
        }
        $data = [];
        $data['uid'] = $input['uid'];

        $wit = db('withdraw')->where('uid',$input['uid'])->where('status',0)->find();
        if(!empty($wit)){
            return $this->ajaxReturn('',-1,'当前有未审核提现');exit;
        }

        $data['type'] = $input['type'];
        $data['name'] = $input['name'];
        $data['card_num'] = $input['number'];
        $data['money'] = $input['money'];
        $data['status'] = 0;
        $data['create_at'] = time();
        $withdrawInfo = db('withdraw_info')->where('uid',$input['uid'])->where('type',$input['type'])->find();
        if ($withdrawInfo) {
            if ($input['type'] == 1) {
                db('withdraw_info')->where('uid',$input['uid'])->update(['card_number'=>$input['number'],'update_at'=>time()]);
            }
        }else{
            $info = [
                'uid' => $input['uid'],
                'type' => $input['type'],
                'name' => $input['name'],
                'card_number' => $input['number'],
                'created_at' => time()
            ];
            db('withdraw_info')->insertGetId($info);
        }
        $res = db('withdraw')->insertGetId($data);
        if ($res) {
            return $this->ajaxReturn($data);
        }else {
            return $this->ajaxReturn('',-1,'插入失败');
        }
    }
    /**
     * 提现余额信息
     */
    public function withdrawInfo() {
        $input = input();
        if (empty($input['uid'])){
            return $this->ajaxReturn('',-1,'未定义uid');
        }
        $data = [];
        $where['uid'] = ['=',$input['uid']];
        $data['info'] = db('withdraw_info')->where($where)->select();
        $where['status'] = ['=',2];
        $total_yj = $this->teamTotal($input['uid'],1);//总佣金
        $total_rw = db('income')->where($where)->sum('money');//总任务收入

        // $res = db('region')->where('uid',$input['uid'])->find();
        // if($res){
        //     $user = db('user_account')->where('id',$input['uid'])->find();
        //     $region_total = $this->region_total($input['uid'],$user['province'],$user['city'],$user['county']);
        // }else{
        //     $region_total =0;
        // }
        

        $total_sr = $total_yj + $total_rw;//总收入
        $where['status'] = ['=',1];
        $total_tx = db('withdraw')->where($where)->sum('money');//总提现
        $balance = $total_sr - $total_tx;
        // $data['balance'] = $balance;
        $data['balance'] = number_format($balance,2,".","");//保留2位小数
        return $this->ajaxReturn($data);
    }
    /**
     * 提现记录
     */
    public function withdrawRecord() {
        $input = input();
        if (empty($input['uid'])){
            return $this->ajaxReturn('',-1,'未定义uid');
        }
        $arr = [];
        $data = db('withdraw')->where('uid',$input['uid'])->order('id desc')->select();
        foreach ($data as $key => $value) {
            $value['create_at'] = date('Y-m-d H:i:s',$value['create_at']);
            $arr[$key] = $value;
        }
        return $this->ajaxReturn($arr);
    }
    /**
     * 总收入记录
     */
    public function incomeRecord() {
        $input = input();
        $sort = [];
        $arrData = [];
        if (empty($input['uid'])){
            return $this->ajaxReturn('',-1,'未定义uid');
        }
        $taskData = db('income')->where('uid',$input['uid'])->where('status',2)->select();//个人任务收益
        foreach ($taskData as $key => $value) {
            $value['created_at'] = date('Y-m-d H:i:s',$value['created_at']);
            $value['update_at'] = date('Y-m-d H:i:s',$value['update_at']);
            $value['typeData'] = 1;
            $taskData[$key] = $value;
            $sort[] =  $value['update_at'];
            $arrData[] =  $value;
        }
        $teamData = $this->teamIncome($input['uid'],1);
        foreach ($teamData as $key => $value) {
            $value['typeData'] = 2;
            $sort[] =  $value['created_at'];
            $arrData[] =  $value;
        }
        
        $res = db('region')->where(['uid'=>$input['uid'],'status'=>2])->find();//判断是否代理
        if($res){
            // $region_total = $this->region_total($input['uid'],$res['province'],$res['city'],$res['county']);
            $region_total = db('region_commission')->where('uid',$input['uid'])->select();
            foreach ($region_total as $key => $value) {
                $value['created_at'] = date('Y-m-d H:i:s',$value['created_at']);
                $value['typeData'] = 3;
                $region_total[$key] = $value;
                $sort[] =  $value['created_at'];
                $arrData[] =  $value;
            }
            // $data = [
            //     'taskData'=> $taskData,//个人任务收益
            //     'teamData'=> $teamData,//团队佣金收益
            //     'region_total'=>$region_total//区域代理
            // ];
        }
        // else{
             
        //     $data = [
        //         'taskData'=> $taskData,//个人任务收益
        //         'teamData'=> $teamData//团队佣金收益
        //     ];

        // }
        array_multisort($sort,SORT_DESC,$arrData);
        return $this->ajaxReturn($arrData);
        // return $this->ajaxReturn($data);
    }
    /**
     * 今日收入记录
     */
    public function todayRecord() {
        $input = input();
        $sort = [];
        $arrData = [];
        if (empty($input['uid'])){
            return $this->ajaxReturn('',-1,'未定义uid');
        }
        $where['uid'] = ['=',$input['uid']];
        $where['status'] = ['=',2];
        $where['update_at'] = ['between',[strtotime(date('Y-m-d 00:00:00')),strtotime(date('Y-m-d 23:59:59'))]];
        $taskData = db('income')->where($where)->select();//个人任务收益
        foreach ($taskData as $key => $value) {
            $value['typeData'] = 1;
            $value['created_at'] = date('Y-m-d H:i:s',$value['created_at']);
            $value['update_at'] = date('Y-m-d H:i:s',$value['update_at']);
            $taskData[$key] = $value;
            $sort[] =  $value['update_at'];
            $arrData[] =  $value;
        }

        $teamData = $this->teamIncome($input['uid'],2);
        foreach ($teamData as $key => $value) {
            $value['typeData'] = 2;
            $sort[] =  $value['created_at'];
            $arrData[] =  $value;
        }
        
        $res = db('region')->where(['uid'=>$input['uid'],'status'=>2])->find();//判断是否代理

        if($res){
            // $where = "to_days('created_at') = to_days(now())";
            // $region_total = $this->region_total($input['uid'],$res['province'],$res['city'],$res['county'],$where);
            $where1['uid'] = ['=',$input['uid']];
            $where1['created_at'] = ['between',[strtotime(date('Y-m-d 00:00:00')),strtotime(date('Y-m-d 23:59:59'))]];
            $region_total = db('region_commission')->where($where1)->select();
            foreach ($region_total as $key => $value) {
                $value['typeData'] = 3;
                $value['created_at'] = date('Y-m-d H:i:s',$value['created_at']);
                $sort[] =  $value['created_at'];
                $arrData[] =  $value;
            }
            // $data = [
            //     'taskData'=> $taskData,//个人任务收益
            //     'teamData'=> $teamData,//团队佣金收益
            //     'region_total'=>$region_total//区域代理
            // ];
        }
        // else{
             
        //     $data = [
        //         'taskData'=> $taskData,//个人任务收益
        //         'teamData'=> $teamData//团队佣金收益
        //     ];

        // }
        array_multisort($sort,SORT_DESC,$arrData);
        return $this->ajaxReturn($arrData);
        // return $this->ajaxReturn($data);

    }
        /**
     *  获取团队的收入记录
     *  type:1总收入，2今日收入
     */
    public function teamIncome($uid,$type) {
        $data = [];
        $where =[];
        $where['uid'] = ['=',$uid];
        if ($type == 2) {
            $where['created_at'] = ['between',[strtotime(date('Y-m-d 00:00:00')),strtotime(date('Y-m-d 23:59:59'))]];
        }
        $team1_commission = db('team1_commission')->where($where)->select();
        foreach ($team1_commission as $key => $value) {
            $value['created_at'] = date('Y-m-d H:i:s',$value['created_at']);
            $data[] = $value;
        }
        $team2_commission = db('team2_commission')->where($where)->select();
        foreach ($team2_commission as $key => $value) {
            $value['created_at'] = date('Y-m-d H:i:s',$value['created_at']);
            $data[] = $value;
        }
        return $data;
    }
    /**
     * 获取团队佣金
     * type:1总佣金，2今日佣金
     */
    public function teamTotal($uid,$type) {
        $team1_commission = 0;
        $team2_commission = 0;
        if ($type == 1) {
            $team1_rw = db('team1_commission')->where(['uid'=>$uid,'type'=>1])->sum('commission');
            $team1_cz = db('team1_commission')->where(['uid'=>$uid,'type'=>2])->sum('commission');
            $team2_rw = db('team2_commission')->where(['uid'=>$uid,'type'=>1])->sum('commission');
            $team2_cz = db('team2_commission')->where(['uid'=>$uid,'type'=>2])->sum('commission');
            $region_rw = db('region_commission')->where(['uid'=>$uid,'type'=>1])->sum('commission');
            $region_cz = db('region_commission')->where(['uid'=>$uid,'type'=>2])->sum('commission');
        } else {
            $where['uid'] = ['=',$uid];
            $where['created_at'] = ['between',[strtotime(date('Y-m-d 00:00:00')),strtotime(date('Y-m-d 23:59:59'))]];
            $where['type'] = ['=',1];
            $team1_rw = db('team1_commission')->where($where)->sum('commission');
            $team2_rw = db('team2_commission')->where($where)->sum('commission');
            $region_rw = db('region_commission')->where($where)->sum('commission');
            $where['type'] = ['=',2];
            $team1_cz = db('team1_commission')->where($where)->sum('commission');
            $team2_cz = db('team2_commission')->where($where)->sum('commission');
            $region_cz = db('region_commission')->where($where)->sum('commission');
        }
        // $team1_commission = ($team1_rw * $task_tc1 / 100) + ($team1_cz * $recharge_tc1 / 100);
        // $team2_commission = ($team2_rw * $task_tc2 / 100) + ($team2_cz * $recharge_tc2 / 100);
        // $region_commission = ($region_rw * $region_rwtc / 100) + ($region_cz * $region_cztc / 100);
        $team1_commission = $team1_rw + $team1_cz;
        $team2_commission = $team2_rw + $team2_cz;
        $region_commission = $region_rw + $region_cz;
        $commission = $team1_commission + $team2_commission + $region_commission;
        return $commission;
    }
}